<script setup lang="ts">
import { ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox } from 'element-plus';
import { Icon } from '@iconify/vue';
import { reactive, ref, h } from 'vue';
import { useUserStore } from '@/store/modules/user';
import type { FormInstance, FormRules } from 'element-plus';
import Message from '@/components/basic/message';
import { to } from '@/utils/awaitTo';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

const userStore = useUserStore();

const message = new Message();

type Callback = {
  // 重载签名：允许不接收参数
  (): void;
  // 重载签名：接收一个参数
  (err: Error | undefined): void;
};

const createValidator = (message: string) => {
  const validator = (_: object, value: string, callback: Callback) => {
    if (value.trim() === '') {
      callback(new Error(message));
    } else {
      callback();
    }
  };

  return validator;
};

const ruleForm = reactive({
  username: '',
  password: ''
});

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: createValidator('Please input the username'), trigger: 'blur' }],
  password: [{ validator: createValidator('Please input the password'), trigger: 'blur' }]
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      console.log('submit!');

      const { username, password } = ruleForm;

      message.loading('login...');
      const [err] = await to(userStore.login({ username, password }));
      message.destroy();
      if (err) {
        ElMessageBox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '登录失败，请检查账号密码是否正确'),
            h('br'),
            h('span', null, '如果忘记密码，请联系管理员')
          ]),
          showCancelButton: false,
          confirmButtonText: '确定'
        });
      } else {
        message.success('登录成功！');
        console.log(router.options);

        setTimeout(() => router.replace((route.query?.redirect as string) || '/'), 500);
      }
    } else {
      ElMessage({
        message: '登录失败',
        type: 'error',
        duration: 5000
      });
    }
  });
};
</script>
<template>
  <div class="login-box">
    <div class="login-logo">
      <!-- <svg-icon name="logo" :size="45" /> -->
      <img src="@/assets/logo.png" width="100%" />
      <!-- <h1 class="mb-0 ml-2 text-3xl font-bold">Antdv Admin</h1> -->
    </div>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      size="large"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off">
          <template #prefix> <Icon icon="ant-design:lock-outlined" /></template>
        </el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off">
          <template #prefix>
            <Icon icon="ant-design:user-outlined" />
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <a-button type="primary" html-type="submit" block @click="submitForm(ruleFormRef)"> 登录 </a-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.login-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100vw;
  height: 100vh;
  box-sizing: border-box;
  padding-top: 240px;
  background: url('@/assets/login.svg');
  background-size: 100%;
  min-width: 1240px;

  .login-logo {
    display: flex;
    align-items: center;
    margin-bottom: 30px;

    .svg-icon {
      font-size: 48px;
    }
  }

  :deep(.el-form) {
    width: 400px;

    .ant-col {
      width: 100%;
    }

    .ant-form-item-label {
      padding-right: 6px;
    }
  }
}
</style>
